<template>
    <div>
        <div>

            <div class="add">
                <el-button type="primary" @click="showAddForm = true"
                    style="width: 100px;height: 50px;">添加用户</el-button>
                <el-form :inline="true" class="search-form">
                    <el-form-item label="" style="width: 150px; display: flex;">
                        <el-input v-model="searchStudent" placeholder="请输入学生姓名"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchStudents">搜索</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div>
            <el-dialog title="添加用户" :visible.sync="showAddForm">
                <el-form :model="newUser">
                    <el-form-item label="姓名" :label-width="formLabelWidth">
                        <el-input v-model="newUser.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="学号" :label-width="formLabelWidth">
                        <el-input v-model="newUser.uid" autocomplete="off"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="语文" :label-width="formLabelWidth">
                        <el-input v-model="newUser.chinese" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="英语" :label-width="formLabelWidth">
                        <el-input v-model="newUser.english" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="数学" :label-width="formLabelWidth">
                        <el-input v-model="newUser.math" autocomplete="off"></el-input>
                    </el-form-item> -->
                    <!-- <el-form-item label="借阅书籍" :label-width="formLabelWidth">
                        <el-input v-model="newUser.books" autocomplete="off"></el-input>
                    </el-form-item> -->
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="showAddForm = false" class="cancel-btn">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </div>
            </el-dialog>
        </div>

        <!-- <div>
            <el-dialog title="编辑用户" :visible.sync="showChangeFrom">
                <el-form :model="editUser">
                    <el-form-item label="语文" :label-width="formLabelWidth">
                        <el-input v-model="editUser.chinese" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="英语" :label-width="formLabelWidth">
                        <el-input v-model="editUser.english" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="数学" :label-width="formLabelWidth">
                        <el-input v-model="editUser.math" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="showChangeFrom = false" class="cancel-btn">取 消</el-button>
                    <el-button type="primary" @click="UpdateUser">确 定</el-button>
                </div>
            </el-dialog>
        </div> -->
        <el-dialog title="管理借阅书籍" :visible.sync="showManageDialog">
            <el-table :data="manageUser.books" style="width: 100%">
                <el-table-column prop="name" label="书名"></el-table-column>
                <el-table-column label="借阅时间" width="220">
                    <template slot-scope="scope">
                        <div>{{ scope.row.start_time }}</div>
                        <div>至 {{ scope.row.end_time }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button type="danger" size="mini" @click="deleteBook(scope.$index)">归还</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <div class="table">
            <el-table :data="tableData">
                <el-table-column prop="name" label="姓名" width="200">
                </el-table-column>
                <el-table-column prop="uid" label="学号" width="1400">
                </el-table-column>
                <!-- <el-table-column prop="books" label="借阅书籍" width="1300">
                </el-table-column> -->
                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" circle @click="edit(scope.row)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" circle @click="del(scope.row.id)"></el-button>                       
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="block" style="display: flex;justify-content:center;padding: 20px 20px 0 0 ;margin-top: 30px;">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10]"
                :page-size="pageSize" :current-page="currentPage" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
    </div>


</template>

<script>
import axios from 'axios';
export default {
    methods: {
        handleClick(row) {
            console.log(row);
        },
        // del(id) {
        //     axios.delete(`/user/${id}`).then(() => {
        //         this.tableData = this.tableData.filter(item => item.id != id)
        //     })
        // },
        addUser() {
            const newUser = { ...this.newUser }
            const isValidScore = (score) => {
                return !isNaN(score) && score >= 0 && score <= 150;
            };

            if (!isValidScore(newUser.chinese) || !isValidScore(newUser.english) || !isValidScore(newUser.math)) {
                alert("请输入有效的分数0-150之间的数字");
                return;
            }
            axios.post('/user', newUser).then(res => {
                const newUser = res.data
                this.tableData.push(newUser)
                this.showAddForm = false
                this.newUser = {
                    id: '',
                    name: '',
                    chinese: '',
                    english: '',
                    math: ''
                }
                alert('添加成功')
                console.log('newUser after reset:', this.newUser);
            }).catch(() => {
                alert("输个信息都输不来 菜就多练")
                this.newUser = {
                    id: '',
                    name: '',
                    chinese: '',
                    english: '',
                    math: ''
                }
            })
        },
        // edit(row){
        //     this.showChangeFrom = true;
        //     this.editUser = {...row}
        //     this.editUser.math = '',
        //     this.editUser.english = '',
        //     this.editUser.chinese = ''
        // },        
        // UpdateUser() {
        //         const editUser = { ...this.editUser };

        //         // 验证函数
        //         const isValidScore = (score) => {
        //             return !isNaN(score) && score >= 0 && score <= 150;
        //         };

        //         // 验证 chinesenglish 和 math 字段
        //         if (!isValidScore(editUser.chinese) || !isValidScore(editUser.english) || !isValidScore(editUser.math)) {
        //             alert("请输入有效的分数0-150之间的数字");
        //             return;
        //         }

        //         console.log('Sending updated user:', editUser); // 添加日志

        //         axios.put(`/user/${editUser.id}`, editUser)
        //             .then(response => {
        //                 const updatedUserData = response.data;
        //                 console.log('Updated user data:', updatedUserData); // 添加日志
        //                 this.tableData = this.tableData.map(item => (item.id === editUser.id ? updatedUserData : item));
        //                 this.showChangeFrom = false;
        //                 alert('更新成功');
        //                 this.editUser = {
        //                     id: '',
        //                     name: '',
        //                     chinese: '',
        //                     english: '',
        //                     math: ''
        //                 };
        //                 console.log('editUser after reset:', this.editUser); // 添加日志
        //             })
        //             .catch(error => {
        //                 console.error('Error updating user:', error);
        //                 alert("更新失败，请检查输入信息");
        //                 this.editUser = {
        //                     id: '',
        //                     name: '',
        //                     chinese: '',
        //                     english: '',
        //                     math: ''
        //                 };
        //             });
        //     },
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchData();
            this.currentPage = 1;
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchData();
            console.log(`当前页: ${val}`);
        },
        fetchData() {
            axios.get('/users', {
                params: {
                    page: this.currentPage,
                    pageSize: this.pageSize
                }
            }).then(response => {
                const data = response.data;
                if (data && Array.isArray(data.items)) {
                    this.tableData = data.items; // 更新表格显示的数据
                    this.total = data.total;     // 更新总记录数

                    console.log(data.items)
                } else {
                    console.error('Unexpected response format from server:', data);
                }
            }).catch(error => {
                console.error('Error fetching data:', error);
                // 可选：向用户显示错误信息
                alert('加载数据失败，请稍后再试');
            });
        },
        searchStudents(){
            if(this.searchStudent.trim() !== ''){
                axios.get(`/user/search/${encodeURIComponent(this.searchStudent.trim())}`).then(res => {
                    const searchResults = res.data
                    this.tableData = searchResults
                    if(searchResults.length === 0){
                        alert('没有找到匹配的学生')
                    }
                    this.searchStudent = ''
                }).catch(error => {
                    console.error('搜索失败:', error)
                    alert('搜索过程中发生错误')
                }) 
            }else{
                axios.get('/user').then(res => {
                    this.tableData = res.data
                }).catch(error => {
                    console.error('搜索失败:', error)
                    alert('搜索过程中发生错误')
                })
            }
        },
        edit(row) {
            try {
                // 确保总是处理数组格式
                let booksData = [];

                if (row.books) {
                    // 处理字符串或对象格式
                    const rawData = typeof row.books === 'string' ? JSON.parse(row.books) : row.books;

                    // 转换对象为数组（如果需要）
                    if (rawData && !Array.isArray(rawData)) {
                        booksData = Object.keys(rawData).map(key => ({
                            id: key,
                            ...rawData[key]
                        }));
                    } else {
                        booksData = rawData || [];
                    }
                }

                this.manageUser = {
                    ...row,
                    books: booksData
                };

                this.showManageDialog = true;

                // 调试日志
                console.log('处理后的书籍数据:', {
                    source: row.books,
                    parsed: booksData
                });

            } catch (error) {
                console.error('数据处理失败:', error);
                this.$message.error('数据加载失败');
                this.manageUser = {
                    ...row,
                    books: [] // 确保总是数组
                };
            }
        },
        // 新增确认管理方法
        // async confirmManage() {
        //     try {
        //         // 调用API更新
        //         const response = await this.$axios.put(`/this.manageUser.id}`, {
        //             books: JSON.stringify(this.manageUser.books)
        //         });

        //         if (response.data.code === 200) {
        //             this.$message.success('书籍信息已更新');
        //             this.$emit('refresh'); // 触发父组件刷新
        //         }
        //     } catch (error) {
        //         this.$message.error('更新失败: ' + error.message);
        //     } finally {
        //         this.showManageDialog = false;
        //     }
        // },
        async deleteBook(index) {
            try {
                // 获取书名
                const bookName = this.manageUser.books[index].name;
                const uid = this.manageUser.uid;
                // 确认对话框
                await this.$confirm(`确认用户已归还《${bookName}》？`, '提示', {
                    type: 'warning'
                });

                // 调用API（使用书名删除）
                // await axios.delete(`/books/return?bookName=${encodeURIComponent(bookName)}`);
                await axios.delete(`/user/return`, {
                    params: {
                        bookName: encodeURIComponent(bookName),
                        userId: uid
                    }
                });

                // 前端删除对应书籍
                this.manageUser.books.splice(index, 1);
                this.$message.success('归还成功');

            } catch (error) {
                if (error !== 'cancel') { // 不是用户取消操作才报错
                    this.$message.error('归还失败: ' + (error.response?.data?.message || error.message));
                }
            }
        }
    },
    data() {
        return{
            showManageDialog: false,
            manageUser: {
                uid: '',
                id: '',
                name: '',
                books: []
            },
            tableData:[],
            newUser: {
                name: '',
                id: '',
                chinese: '',
                english: '',
                math: '',
                books:'',
                uid:'',
                createdTime:''
            },
            showAddForm: false,
            formLabelWidth: '120px',
            showChangeFrom: false,
            drawer: false,
            editUser: {
                id: '',
                name: '',
                // chinese: '',
                // english: '',
                // math: ''
                books:'',
            },
            total:0,
            currentPage: 1,
            pageSize: 10,
            searchStudent:''
        }
            
    },
    created() {
        this.fetchData();
    },
}
</script>

<style >
.add{
    display: flex;
    position: relative;
    width: 100px;
    height: 60px;
    border-radius: 5px;
}
.edit{
    position: relative;
    top: -30px;
    left: 200px;
    width: 100px;
    height: 30px;
}
.el-button .cancel-btn {
    width: 100px;
    height: 50px;
    background-color: #f0f0f0;
    /* 示例背景颜色 */
    color: #333;
    /* 示例文字颜色 */
}
.search-form {
    position: absolute;
    height: 50px;
    left: 1200px;
    top: 20px;
    display: flex;
}
.table{
    position: relative;
    top: 50px;
}
</style>


